package com.zjzaki.thingsboard.activity.login;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.zjzaki.thingsboard.R;
import com.zjzaki.thingsboard.activity.main.MainActivity;
import com.zjzaki.thingsboard.dao.ThingsBoardDao;
import com.zjzaki.thingsboard.util.FileHelper;
import com.zjzaki.thingsboard.util.InternetUtil;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etUsername;
    private EditText etPassword;
    //进度对话框
    ProgressDialog staticDialog;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            staticDialog.dismiss();//关闭进度对话框
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        //获得用户名输入框
        etUsername = findViewById(R.id.et_username);
        //获得密码输入框
        etPassword = findViewById(R.id.et_password);

        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                Log.i("Ansen", "内容被改变之前调用" + s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Log.i("Ansen", "内容改变，可以告诉服务器：" + s);
            }

            @Override
            public void afterTextChanged(Editable s) {
//                Log.i("Ansen", "内容改变之后调用" + s);
            }
        });

        // 监听登录按钮状态
        findViewById(R.id.tv_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                Log.i("zjzaki", "点击了登录按钮：" + username + " : " + password);

                //得到网络状态
                boolean serverOk = isServerOk();
                //判断网络状态是否正常
                if (serverOk) {
                    //弹出一个进度提示框
                    staticDialog = ProgressDialog.show(LoginActivity.this, "", "正在登录中");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             * 使线程拥有自己的消息列队，主线程拥有自己的消息列队，
                             * 一般线程创建时没有自己的消息列队，
                             * 消息处理时就在主线程中完成，
                             * 如果线程中使用Looper.prepare()和Looper.loop()
                             * 创建了消息队列就可以让消息处理在该线程中完成
                             */
                            Looper.prepare();
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            boolean login = login(username, password);

                            //关闭
                            handler.sendEmptyMessage(0);
                            if (login) {
                                //跳转界面
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            }
                            Looper.loop();
                        }
                    }).start();
                } else {
                    staticDialog = ProgressDialog.show(LoginActivity.this, "", "网络错误登录失败");
                    //关闭
                    handler.sendEmptyMessageDelayed(0,2000);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
    }

    /**
     * 登录方法
     *
     * @param username 用户名
     * @param password 密码
     * @return 是否登录成功，成功返回true，失败返回false
     */
    public boolean login(String username, String password) {

        //定义接收
        String loginMsg = ThingsBoardDao.login(username, password);

//        //模拟延迟
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();

        //打印日志
        Log.i("loginMsg", loginMsg);
        //解析登录状态
        JSONObject loginJson = JSONObject.parseObject(loginMsg);
        Integer status = loginJson.getInteger("status");
        if (status != null) {
            switch (status) {
                case 401:
                    showDialog(loginJson.getString("message"));
                    Log.i("测试", loginJson.getString("message"));
                    break;
            }
        } else {

            String token = loginJson.getString("token");
            String refreshToken = loginJson.getString("refreshToken");
            String scope = loginJson.getString("scope");
            //写入到文件中
            FileHelper fileHelper = new FileHelper(this.getApplicationContext());
            fileHelper.save("login.txt", token + " " + refreshToken + " " + scope);

            return true;
        }

        return false;
    }

    private boolean loginIsOk(String msg) {
        return false;
    }


    /**
     * 展示弹窗
     *
     * @param msg 提示信息
     */
    private void showDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(msg);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        // 展示弹窗
        builder.create().show();
    }

    /**
     * 检测网络连接是否正常
     *
     * @return true表示正常，false表示异常
     */
    private boolean isServerOk() {
        return new InternetUtil(this).isInternetConnection();
    }
}
